<!DOCTYPE html>
<html>

<head>
  <title>
    <%= title %>
  </title>
  <link rel='stylesheet' href='/stylesheets/index.css' />
</head>

<body>
  <div class="content">
    <div id="chat-container">
      <div id="messages"></div>
      <div class="flex-ac">
        <input type="text" id="input" placeholder="输入你的问题">
        <button id="send">发送</button>
      </div>
    </div>
    <div class="options">
      <p>配置</p>
      <div>
        <input type="radio" id="chatMode1" name="chatMode" value="chat" checked>
        <span>聊天</span>
      </div>
      <div>
        <input type="radio" id="chatMode2" name="chatMode" value="chatPrompt">
        <span>对话</span>
      </div>
      <button class="qs-list">查看问答列表</button>
      <button class="file-list">查看文档列表</button>
    </div>
    <script>
      const qsList = document.querySelector('.qs-list');
      const fsList = document.querySelector('.file-list');

      qsList.addEventListener('click', () => {
        window.location.href = '/qs-list';
      });

      fsList.addEventListener('click', () => {
        window.location.href = '/fs-list';
      });


    </script>
  </div>


  <script>
    const input = document.getElementById('input');
    const send = document.getElementById('send');
    const messages = document.getElementById('messages');

    send.addEventListener('click', () => {
      const message = input.value;
      const chatMode = document.querySelector('input[name="chatMode"]:checked');
      console.log(chatMode.value);

      if (message) {
        const questionElement = document.createElement('p');
        questionElement.textContent = `问: ${message}`;
        questionElement.classList.add('question');
        messages.appendChild(questionElement);
        fetch('/' + chatMode.value, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ message, stream: true })
        })
          .then(response => {
            if (response.code == -1) {
              alert(response.message);
              return;
            }
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let partialText = '';

            function readChunk() {
              return reader.read().then(({ done, value }) => {
                if (done) {
                  if (partialText) {
                    const answerElement = document.createElement('p');
                    answerElement.textContent = `答: ${partialText}`;
                    answerElement.classList.add('answer');
                    messages.appendChild(answerElement);
                  }
                  return;
                }
                const chunk = decoder.decode(value, { stream: true });
                partialText += chunk;
                const lines = partialText.split('\n');
                partialText = lines.pop();
                lines.forEach(line => {
                  const answerElement = document.createElement('p');
                  answerElement.textContent = `${line}`;
                  answerElement.classList.add('answer');
                  messages.appendChild(answerElement);
                });
                // 确保页面渲染完成后再获取下一块数据
                requestAnimationFrame(() => {
                  return readChunk();
                });
              });
            }
            return readChunk();
          })
          .catch(error => {
            console.error('Fetch failed:', error);
          });
        input.value = '';
      }
    });

  </script>
</body>

</html>